import { uniqueId } from 'lodash-es';
import { MockMethod } from 'vite-plugin-mock';

export function range<T = number>(len: number, formatter?: (index: number) => T, start = 0) {
  const arr: T[] = [];
  for (let i = start; i < len + start; i += 1) {
    arr.push((formatter ? formatter(i) : i) as T);
  }
  return arr;
}

const list = range(30, (index) => ({
  id: `${index}`,
  name: `类别${index}`,
  remark: `类别${index}`,
  created: new Date()
}));
export default [
  {
    url: '/api/userType/list',
    method: 'get',
    response: ({ query }) => {
      const { pageNum, pageSize, name } = query;
      const len = pageNum * pageSize;
      const resList = list.filter((i) => i.name.includes(name));
      return {
        code: 200,
        message: '查询成功',
        data: {
          list: resList.slice(len - pageSize, len),
          rowCount: resList.length,
          pageNum,
          pageSize
        }
      };
    }
  },
  {
    url: '/api/userType/all',
    method: 'get',
    response: () => {
      return {
        code: 200,
        message: '查询成功',
        data: list
      };
    }
  },
  {
    url: '/api/userType/add',
    method: 'post',
    response: ({ body }) => {
      const { name, remark } = body;
      const id = uniqueId();
      list.push({ id, name, remark, created: new Date() });
      return {
        code: 200,
        message: '添加成功'
      };
    }
  },
  {
    url: '/api/userType/edit',
    method: 'put',
    response: ({ body }) => {
      const { id, name, remark } = body;
      const index = list.findIndex((i) => i.id === id);
      const info = list[index];
      list.splice(index, 1, { ...info, id, name, remark });
      return {
        code: 200,
        message: '编辑成功'
      };
    }
  },
  {
    url: '/api/userType/del',
    method: 'delete',
    response: ({ body }) => {
      const { id } = body;
      const index = list.findIndex((i) => i.id === id);
      list.splice(index, 1);
      return {
        code: 200,
        message: '添加成功'
      };
    }
  }
] as MockMethod[];
